package com.rpay.service.phone.impl;

import com.rpay.common.dto.sms.SmsCodeDTO;
import com.rpay.common.util.http.HttpUtil;
import com.rpay.common.util.http.request.HttpConfig;
import com.rpay.dao.sms.SmsCodeDao;
import com.rpay.dao.sms.SmsTemplateDao;
import com.rpay.model.sms.SmsCodeDO;
import com.rpay.model.sms.SmsTemplateDO;
import com.rpay.service.phone.IPhoneService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/5/4
 * @version 1.0
 */
@Service
public class PhoneServiceImpl implements IPhoneService {
    @Autowired
    private SmsCodeDao smsCodeDao;
    @Autowired
    private SmsTemplateDao smsTemplateDao;

    @Value("${juhe.sms.key}")
    private String smsKey;
    @Value("${juhe.sms.url}")
    private String smsUrl;

    @Override
    @Transactional
    public boolean sendSmsCode(SmsCodeDTO smsCodeDTO) throws Exception {
        SmsTemplateDO smsTemplateDO = smsTemplateDao.selectByType(smsCodeDTO.getVerifyType());
        if (smsTemplateDO == null) {
            return false;
        }
        SmsCodeDO smsCodeDO = convertDTOToDO(smsCodeDTO);
        smsCodeDao.insert(smsCodeDO);
        send(smsTemplateDO.getTplId(), smsCodeDO);
        return true;
    }

    private int send(Integer tplId, SmsCodeDO smsCodeDO) throws Exception {
        HttpConfig httpConfig = HttpConfig.custom()
                .param("mobile", smsCodeDO.getReceiver())
                .param("key", smsKey)
                .param("tpl_id", tplId.toString())
                .param("tpl_value", "%23code%23%3d" + smsCodeDO.getCode());
        String str = HttpUtil.get(httpConfig.url(smsUrl));
        JSONObject jsonObject = new JSONObject(str);
        return jsonObject.getInt("error_code");
    }

    private SmsCodeDO convertDTOToDO(SmsCodeDTO smsCodeDTO) {
        SmsCodeDO smsCodeDO = new SmsCodeDO();
        if (smsCodeDTO != null) {
            smsCodeDO.setCode(smsCodeDTO.getCode());
            smsCodeDO.setReceiver(smsCodeDTO.getReceiver());
            smsCodeDO.setVerifyType(smsCodeDTO.getVerifyType());
            smsCodeDO.setType("PHONE");
        }
        return smsCodeDO;
    }


}
